import plugins from './plugins.js'
import toolbar from './toolbar.js'
import load from './dynamicLoadScript.js'
import { addIndent2em, addMaxLimit } from './extraPlugin.js'
const tinymceCDN = 'https://cdn.lishicloud.com/cdn/tinymce/tinymce.js'

export default {
  name: 'Editor',
  props: {
    id: {
      type: String,
      default: function() {
        return 'vue-tinymce-' + +new Date() + ((Math.random() * 1000).toFixed(0) + '')
      }
    },
    value: {
      type: String,
      default: ''
    },
    menubar: {
      type: String,
      default: 'file edit insert view format table'
    },
    height: {
      type: [Number, String],
      required: false,
      default: 360
    },
    width: {
      type: [Number, String],
      required: false,
      default: 'auto'
    },
    disabled: {
      type: Boolean,
      default: false
    },
    uploadHandler: {
      type: Function,
      default: (formData, succFun, failFun) => {
        failFun('使用上传功能请配置上传方法')
      }
    },
    maxLength: {
      type: Number,
      default: 50000
    },
    placeholder: {
      type: String,
      default: '请输入'
    },
    plugins: {
      type: Array,
      default: () => plugins
    },
    toolbar: {
      type: Array,
      default: () => toolbar
    },
    contentStyle: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      hasChange: false,
      hasInit: false,
      tinymceId: this.id,
      fullscreen: false,
      languageTypeList: {
        'en': 'en',
        'zh': 'zh_CN',
        'es': 'es_MX',
        'ja': 'ja'
      }
    }
  },
  computed: {
    containerWidth() {
      const width = this.width
      if (/^\d+(\.\d+)?$/.test(width)) { // matches `100`, `'100'`
        return `${width}px`
      }
      return width
    }
  },
  watch: {
    value: {
      handler: function (val) {
        if (!this.hasChange && this.hasInit) {
          this.$nextTick(() => {
            window.tinymce.get(this.tinymceId).setContent(val || '')
          })
        }
      }
    }
  },
  mounted() {
    this.init()
  },
  activated() {
    if (window.tinymce) {
      this.initTinymce()
    }
  },
  deactivated() {
    this.destroyTinymce()
  },
  destroyed() {
    this.destroyTinymce()
  },
  methods: {
    init() {
      // dynamic load tinymce from cdn
      load(tinymceCDN, (err) => {
        if (err) {
          this.$message.error(err.message)
          return
        }
        addIndent2em()
        const maxLimit = this.maxLength || 50000
        addMaxLimit(maxLimit, `超过最大输入${maxLimit}字符!`)
        this.initTinymce()
      })
    },
    initTinymce() {
      const _this = this
      const initOptions = (updateValue) => {
        return {
          selector: `#${this.tinymceId}`,
          content_style: this.contentStyle,
          language: this.languageTypeList['zh'],
          language_url: 'https://cdn.lishicloud.com/cdn/tinymce/langs/zh_CN.js', // site absolute URL
          height: this.height,
          body_class: 'panel-body ',
          object_resizing: false,
          toolbar: this.toolbar.length > 0 ? this.toolbar : toolbar,
          menubar: this.menubar,
          end_container_on_empty_block: true,
          external_plugins: {
            powerpaste: 'https://cdn.lishicloud.com/cdn/tinymce/plugins/powerpaste/plugin.js',
          },
          powerpaste_allow_local_images: true,
          powerpaste_word_import: 'prompt',
          powerpaste_html_import: 'prompt',
          plugins: plugins,
          code_dialog_height: 450,
          code_dialog_width: 1000,
          advlist_bullet_styles: 'square',
          advlist_number_styles: 'default',
          imagetools_cors_hosts: ['www.tinymce.com', 'codepen.io'],
          default_link_target: '_blank',
          link_title: false,
          readonly: this.disabled,
          placeholder: this.placeholder,
          nonbreaking_force_tab: true, // inserting nonbreaking space &nbsp; need Nonbreaking Space Plugin
          init_instance_callback: editor => {
            if (_this.value) {
              editor.setContent(_this.value)
            }
            _this.hasInit = true
            editor.on('NodeChange Change KeyUp SetContent', () => {
              const content = editor.getContent()
              content && (this.hasChange = true)
              if(this.hasChange) {
                updateValue(editor)
                this.$emit('change', content)
              }
            })
          },
          setup(editor) {
            editor.on('FullscreenStateChanged', (e) => {
              _this.fullscreen = e.state
            })
          },
          images_upload_handler: (blobInfo, succFun, failFun) => {
            const formData = new FormData();
            const file = blobInfo.blob();//转化为易于理解的file对象
            formData.append('file', file);//此处与源文档不一样
            this.uploadHandler(formData, succFun, failFun)
          },
          file_picker_types: 'media',
          file_picker_callback: (cb, value, meta) => {
            if (meta.filetype === 'media') {
              const input = document.createElement('input') //创建一个隐藏的input
              input.setAttribute('type', 'file')
              input.setAttribute('display', 'none')
              input.setAttribute('accept', '.mp4,.mov,.wmv,.flv,.avi,.avchd,.webm,.mkv')
              input.onchange = () => {
                const file = input.files[0] //选取第一个文件
                const formData = new FormData();
                formData.append('file', file);//此处与源文档不一样
                this.uploadHandler(formData, cb, (e) => {this.$message.error(e)})
              }
              //触发点击
              input.click()
            }
          },
          convert_urls: false
        }
      }
      window.tinymce.init(initOptions(this.updateValueFn))
    },
    destroyTinymce() {
      const tinymce = window.tinymce.get(this.tinymceId)
      if (this.fullscreen) {
        tinymce.execCommand('mceFullScreen')
      }

      if (tinymce) {
        tinymce.destroy()
      }
    },
    setContent(value) {
      window.tinymce.get(this.tinymceId).setContent(value)
    },
    getContent() {
      window.tinymce.get(this.tinymceId).getContent()
    }
  }
}
